package com.qingcheng.controller;


import com.alibaba.dubbo.config.annotation.Reference;
import com.qingcheng.controller.utils.WebUtil;
import com.qingcheng.pojo.system.LoginLog;
import com.qingcheng.service.system.LoginLogService;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

public class AuthenticationSuccessHandlerImpl implements AuthenticationSuccessHandler {

    @Reference
    private LoginLogService loginLogService;
    /**
     * 定义security登录成功处理器
     * @param request
     * @param response
     * @param authentication
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //创建登录日志对象
        LoginLog loginLog=new LoginLog();
        //获取认证人登录名
        loginLog.setLoginName(authentication.getName()); //存入登录用户名信息
        //获取ip
        String ip = request.getRemoteAddr();
        loginLog.setIp(ip);                               //存入ip地址
        //工具类获取ip所在城市
        String city = WebUtil.getCityByIP(ip);
        loginLog.setLocation(city);                       //存入ip所在城市
        //获取浏览器信息
        String agent = request.getHeader("user-agent");
        //使用工具类获取浏览器信息
        String browserName = WebUtil.getBrowserName(agent);
        loginLog.setBrowserName(browserName);           //存入浏览器名称
        loginLog.setLoginTime(new Date());              //存入登录时间

        //存入数据进数据库
        loginLogService.add(loginLog);
        //请求转发到主页
        request.getRequestDispatcher("/main.html").forward(request,response);
    }
}
